<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

use AliyunMNS\Client;
use AliyunMNS\Requests\SendMessageRequest;
use AliyunMNS\Requests\CreateQueueRequest;
use AliyunMNS\Exception\MnsException;

use Swoole\Coroutine;
use Swoole\Timer;
use Swoole\Coroutine\MySQL;
use Swoole\Coroutine\Redis;
use App\Models\Cabinet;
use Illuminate\Support\Str;

class Alimns extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'ali-mns';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command. 
     *
     * @return mixed
     */
    public function handle()
    {
        $client = new Client('http://1960429774320704.mns.cn-shanghai.aliyuncs.com', 'LTAIXidsHeo1vYeo', 'vO9c9Yqyha6PNAkFyb4jAQPfJ5rvbU');

        $queueName = 'aliyun-iot-a1BbirCKf77';

        Timer::tick(1000, function (int $timer_id) use ($client, $queueName) {
            $this->receiveMsg($client, $queueName);
        });
        \Swoole\Event::wait();
        return;
    }

    protected function receiveMsg($client, $queueName){
        $queue = $client->getQueueRef($queueName);
        $receiptHandle = NULL;
        try {
            $res = $queue->receiveMessage();
            $receiptHandle = $res->getReceiptHandle();
            $msg = json_decode($res->getMessageBody());
            $this->deleteMsg($queue, $receiptHandle);   //拿到消息后删除
            $type = $msg->messagetype;
            if ($type == 'upload') {
                $swooleMysql = new MySQL();
                $swooleMysql->connect([
                    'host'     => env('DB_HOST'),
                    'port'     => env('DB_PORT'),
                    'user'     => env('DB_USERNAME'),
                    'password' => env('DB_PASSWORD'),
                    'database' => env('DB_DATABASE'),
                ]);
                $insertSql = 'INSERT INTO `xfy_cabinet_data_second`(`cabinet_id`, `data`, `created_time`) VALUES ';
                $insertValue = '';

                $swooleRedis = new Redis();
                $swooleRedis->connect(env('REDIS_HOST'), env('REDIS_PORT'));
                $swooleRedis->auth(env('REDIS_PASSWORD'));

                $json = base64_decode($msg->payload);
                // var_dump($json)."\n";
                $arr = json_decode($json, true);
                foreach ($arr as $oneCabinet) {
                    if (isset($oneCabinet['vbox']) && isset($oneCabinet['ip'])) {
                        $querySql = 'SELECT `id` FROM `xfy_cabinets` WHERE `pid` = (SELECT `id` FROM `xfy_cabinets` WHERE `machine_code` = \''.$oneCabinet['vbox'].'\') AND `name` = \''.$oneCabinet['ip'].'\' AND `show` = 1';
                        $queryRes = $swooleMysql->query($querySql);
                        if ($queryRes) {
                            $cabinetId = reset($queryRes)['id'];
                            $createdTime = strtotime($oneCabinet['date']);
                            unset($oneCabinet['vbox']);
                            unset($oneCabinet['ip']);
                            unset($oneCabinet['date']);
                            unset($oneCabinet['iccid']);
                            if ($oneCabinet) {
                                $pointsSql = 'SELECT `alias` FROM `xfy_cabinet_points` WHERE `cabinet_id` = '.$cabinetId.';';
                                $pointsRes = $swooleMysql->query($pointsSql);
                                $insertData = [];
                                foreach ($pointsRes as $onePoint) {
                                    $insertData[$onePoint['alias']] = 0;
                                }
                                       
                                foreach ($oneCabinet as $point => $pointValue) {
                                    $insertData['a_'.$point] = round($pointValue,3);
                                }
                                $insertValue .= '('.$cabinetId.', \''.addslashes(json_encode($insertData)).'\', '.$createdTime.'),';

                                // 入缓存
                                $redisPrefix = env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_');
                                $cacheKey = $redisPrefix.Cabinet::CACHE_KEY_.$cabinetId;
                                $swooleRedis->set($cacheKey, json_encode($insertData));
                            }
                        }
                    }
                }
                if ($insertValue) {
                    $sql = $insertSql.rtrim($insertValue, ',');
                    $res = $swooleMysql->query($sql);
                    // var_dump($res);
                }
            }
        } catch (MnsException $e) {
            error_log(date("Y-m-d H:i:s")." ReceiveMessage Failed: " . $e."\n",3,'/tmp/alimns.log');
        }
    }

    protected function deleteMsg($queue, $receiptHandle){
        try {
            $res = $queue->deleteMessage($receiptHandle);
        } catch (MnsException $e) {
            error_log(date("Y-m-d H:i:s")." DeleteMessage Failed: " . $e."\n",3,'/tmp/alimns.log');
        }
    }
}
